package com.zzty.zzlp.controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
public class LoginController {

    @RequestMapping("/login")
    public void loginPage(HttpServletResponse response){
        try {
            response.sendRedirect("/zzlp/html/login.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/login/addInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Boolean addInfo (@RequestParam(value = "files") MultipartFile [] files) {
        Boolean flag = false;
        try {
            if (files!=null) {
                for (MultipartFile file:files) {
                    String filepath = "C://temp//avatar//"+file.getOriginalFilename();
                    flag = (copyFile(file,filepath));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static Boolean copyFile (MultipartFile tempFile, String filePath) {
        Boolean res = false;
        try {
            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            // 将文件拷贝到当前目录下
            tempFile.transferTo(file);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    @RequestMapping(value = "login/logout")
    @ResponseBody
    public Boolean logout(HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession(false);
        if(session == null){
            return true;
        }
        session.removeAttribute("User");
        return true;
    }
}
